import pygame
import random

# 初始化Pygame
pygame.init()

# 设置窗口大小和标题
screen_width = 640
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Snake Game")

# 定义颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)

# 定义蛇和食物的大小和速度
snake_size = 20
snake_speed = 10
food_size = 20
food_speed = 5

# 创建蛇和食物的初始位置
snake_pos = [[100, 50], [90, 50], [80, 50]]
food_pos = [random.randint(10, screen_width - food_size), random.randint(10, screen_height - food_size)]
food_spawn = True

# 创建时钟对象以控制帧率
clock = pygame.time.Clock()

# 游戏主循环
while True:
    # 处理退出事件
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()

            # 绘制背景和食物
    screen.fill(BLACK)
    pygame.draw.rect(screen, GREEN, [food_pos[0], food_pos[1], food_size, food_size])


    print(snake_pos)
    # 移动蛇
    if snake_pos[-1][0] >= screen_width - snake_size and snake_pos[-1][0] <= screen_width:
        snake_pos[-1][0] -= snake_speed
    elif snake_pos[-1][0] < screen_width - snake_size:
        snake_pos[-1][0] += snake_speed
    elif snake_pos[-1][0] > screen_width:
        snake_pos[-1][0] -= snake_speed
    if snake_pos[-1][1] >= screen_height - snake_size and snake_pos[-1][1] <= screen_height:
        snake_pos[-1][1] -= snake_speed
    elif snake_pos[-1][1] < screen_height - snake_size:
        snake_pos[-1][1] += snake_speed
    elif snake_pos[-1][1] > screen_height:
        snake_pos[-1][1] -= snake_speed
    for block in snake_pos[:-1]:
        if block == snake_pos[-1]:
            snake_pos.pop()
            break
    else:
        snake_pos.pop()
        if food_spawn:
            food_pos = [random.randint(10, screen_width - food_size), random.randint(10, screen_height - food_size)]
            food_spawn = False
        else:
            food_spawn = True
            score = len(snake_pos) - 2
            if score > 0:
                font = pygame.font.Font(None, 36)
                text = font.render("Score: " + str(score), True, WHITE)
                screen.blit(text, (10, 10))
            else:
                font = pygame.font.Font(None, 36)
                text = font.render("Game Over", True, RED)